/**
 * User: Clinton Begin
 * Date: Jul 13, 2003
 * Time: 7:21:30 PM
 */
package com.juanfrivaldes.cio2005.persistence.sqlmapdao;

import org.springframework.dao.DataAccessException;
import org.springframework.dao.DataRetrievalFailureException;
import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;


public class SecuenciaSqlMapDao extends SqlMapClientDaoSupport{



  /**
   * This is a generic sequence ID generator that is based on a database
   * table called 'SEQUENCE', which contains two columns (NAME, NEXTID).
   * <p/>
   * This approach should work with any database.
   *
   * @param name The name of the sequence.
   * @return The Next ID
   * @
   */
  public synchronized int getNextId(String name) throws DataAccessException{
    Secuencia sequence = new Secuencia(name, -1);

    sequence = (Secuencia) getSqlMapClientTemplate().queryForObject("getSequence", sequence);
    if (sequence == null) {
      throw new DataRetrievalFailureException("Error: A null sequence was returned from the database (could not get next " + name + " sequence).");
    }
    Object parameterObject = new Secuencia(name, sequence.getNextId() + 1);
    getSqlMapClientTemplate().update("updateSequence", parameterObject);

    
    return sequence.getNextId();
  }

}
